import { useState, useEffect, useRef, useCallback } from 'react'

interface ListItem {
  id: number
  title: string
  overview: string
  cover: string
}

const List = () => {
  const [items, setItems] = useState<ListItem[]>([])
  const [loading, setLoading] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const observerRef = useRef<HTMLDivElement>(null)
  const pageRef = useRef(1)

  // 模拟数据生成函数
  const generateItems = (page: number, pageSize: number = 10): ListItem[] => {
    const items: ListItem[] = []
    const startId = (page - 1) * pageSize + 1
    
    // 模拟数据有限，总共只有50条数据
    const totalItems = 50
    const remainingItems = Math.max(0, totalItems - (startId - 1))
    const currentPageSize = Math.min(pageSize, remainingItems)
    
    for (let i = 0; i < currentPageSize; i++) {
      const id = startId + i
      items.push({
        id,
        title: `文章标题 ${id}`,
        overview: `这是第 ${id} 篇文章的概述内容。这里可以包含文章的摘要信息，让用户快速了解文章的主要内容。`,
        cover: `https://picsum.photos/300/200?random=${id}`
      })
    }
    return items
  }

  // 加载更多数据
  const loadMore = useCallback(async () => {
    if (loading || !hasMore) return
    
    setLoading(true)
    
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      const newItems = generateItems(pageRef.current)
      
      if (newItems.length === 0) {
        setHasMore(false)
      } else {
        setItems(prev => [...prev, ...newItems])
        pageRef.current += 1
        
        // 如果返回的数据少于请求的数量，说明没有更多数据了
        if (newItems.length < 10) {
          setHasMore(false)
        }
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      // 可以添加错误状态处理
    } finally {
      setLoading(false)
    }
  }, [loading, hasMore])

  // 初始化数据
  useEffect(() => {
    if (items.length === 0) {
      loadMore()
    }
  }, [loadMore, items.length])

  // 设置交叉观察器
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
          loadMore()
        }
      },
      {
        threshold: 0.1,
        rootMargin: '100px'
      }
    )

    const currentObserverRef = observerRef.current
    if (currentObserverRef) {
      observer.observe(currentObserverRef)
    }

    return () => {
      if (currentObserverRef) {
        observer.unobserve(currentObserverRef)
      }
    }
  }, [loadMore, hasMore, loading])

  return (
    <div className="infinite-scroll-container">
      <h1 className="list-title">无限滚动列表</h1>
      
      <div className="list-grid">
        {items.map((item) => (
          <div key={item.id} className="list-item">
            <div className="item-cover">
              <img src={item.cover} alt={item.title} />
            </div>
            <div className="item-content">
              <h2 className="item-title">{item.title}</h2>
              <p className="item-overview">{item.overview}</p>
            </div>
          </div>
        ))}
      </div>

      {/* 加载指示器 */}
      <div ref={observerRef} className="loading-indicator">
        {loading && (
          <div className="loading-spinner">
            <div className="spinner"></div>
            <p>加载中...</p>
          </div>
        )}
        {!hasMore && !loading && (
          <div className="no-more">
            <p>没有更多内容了</p>
          </div>
        )}
      </div>
    </div>
  )
}

export default List